import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { MdDatepickerModule } from '@angular/material';
import { DatePipe } from '@angular/common';
import { List } from 'linqts';
import { Tag } from '../../../entity/tag.model'
import { ITdDataTableColumn, TdDataTableComponent, IPageChangeEvent, TdDataTableService } from '@covalent/core';
import { NzMessageService } from 'ng-zorro-antd';
import { TurbEarlyWarn, StateGroups, WarmCount } from '../../../entity/turb-early-warn.model';
import { TurbEarlyWarnService } from '../../../service/turb-early-warn.service';
import { Device } from '../../../entity/device.model';
import { FarmCategoryEnum } from '../../common/device-tag-selector/farm-category.enum';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';

import { EarlyWarningService } from '../../../service/early-warning.service';
import { LazyLoadEvent } from 'primeng/components/common/api';
import { ApplicationService } from '../../../service/application.service';

@Component({
	selector: '',
	templateUrl: './warn-search.component.html',
	styleUrls: ['./warn-search.component.css']
})
export class WarnSearchComponent implements OnInit {
	public deviceCategories: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine, DeviceCategoryEnum.inverter];
	private original: TurbEarlyWarn[] = [];
	public stateGroups: StateGroups[] = [];
	public turbEarlyWarns: WarmEarly[] = [];
	public warms: WarmEarly[] = [];
	public warmCountData: WarmCount[] = [];
	public warmCountFilterData: WarmCount[] = [];

	private h = 1000 * 3600;

	/**
	* 风机、测点ids集合
	*
	* @type @memberof WarnSearchComponent
	*/
	private turbineIds: number[] = [];
	public active: number = 0;
	public endTime = new Date();
	public startTime: Date = new Date(this.endTime.getFullYear(), this.endTime.getMonth(), this.endTime.getDate());

	/**
	 * 预警模糊查询
	 *
	 * @memberof WarnSearchComponent
	 */
	public divWarnName: string;
	/**
	 * 每页条数
	 */
	// public limit: number = 10;
	/**
   * 分页中，每页显示的条数
   */
	public pageSize: number;
	/**
	 * 是否显示进度条
	 */
	isShowBar: boolean = true;

	/**
	 * 本地缓存的数据
	 */
	public allTurbEarlyWarns = [];
	public event: any;
	public count: number = 0;//总条数
	public sortField: string;//排序字段
	public sortOrder: number;//正序1，倒序-1；
	/**
	 *风机最大选择数量
	 *
	 * @type {number}
	 * @memberof WarnSearchComponent
	 */
	public deviceCountLimit: number;
	/**
   *刚进页面是默认选择风机数量
   *默认:null 不做限制
   * 0不选择
   * @memberof WarnSearchComponent
   */
	defaultChooseDeviceCount;
	en: any;
	constructor(
		private turbEarlyWarnService: TurbEarlyWarnService,
		private _message: NzMessageService,
		private earlyWarningService: EarlyWarningService,
		private application: ApplicationService,

	) {
	}
	ngOnInit() {
		this.en = {
			firstDayOfWeek: 0,
			dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
			dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
			dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
			monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
			monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
			today: '今天',
			clear: '清除'
		};
		if (this.application.currentMenuParams && this.application.currentMenuParams['pageSize']) {
			this.pageSize = Number(this.application.currentMenuParams['pageSize'].paramValue);
		} else {
			this.pageSize = 15;
		}
		if (this.application.currentMenuParams && this.application.currentMenuParams['deviceCountLimit']) {
			this.deviceCountLimit = Number(this.application.currentMenuParams['deviceCountLimit'].paramValue);
		} else {
			this.deviceCountLimit = null;
		}
		if (this.application.currentMenuParams && this.application.currentMenuParams['defaultChooseDeviceCount']) {
			this.defaultChooseDeviceCount = Number(this.application.currentMenuParams['defaultChooseDeviceCount'].paramValue);
		} else {
			this.defaultChooseDeviceCount = null;
		}

	}

	/**

		ngOnInit() {
			this.loadData(50, null, null);
		}

		loadData(top, startTime, endTime) {
			this.earlyWarningService.getSysRTurbEarlyWarningList(top, startTime, endTime)
				.then(res => {
					this.warms = [];
					this.turbEarlyWarns = [];
					this.original = [];
					this.original = [...res];
					this.original.forEach(o => {
						const warm: WarmEarly = {
							stateName: o.stateName,
							stateColor: o.stateColor,
							tagDesc: o.farmName + o.deviceName + o.tagName,
							startTime: o.startTime,
							endTime: o.endTime,
							maxVal: o.maxVal,
							minVal: o.minVal
						}
						this.warms.push(warm);
					});
					this.turbEarlyWarns = [...this.warms];
					this.groupByStateName([...this.warms]);
					this.onCountWarms([...res]);
				})
				.catch(error => {
					console.log(' has error', error);
				})
		}

	 */
	ngOnDestroy() {
		//组件销毁的钩子
		this.allTurbEarlyWarns = [];
	}

	/**
	 *
	 * @param event 懒加载
	 */
	loadCarsLazy(event: LazyLoadEvent) {
		clearTimeout(timer);
		var timer = setTimeout(() => {
			this.event = event;
			if (this.sortField !== event.sortField || this.sortOrder !== event.sortOrder) {
				//排序的时候清空
				this.allTurbEarlyWarns = [];
			}
			if (this.allTurbEarlyWarns[(event.first + this.pageSize) / this.pageSize]) {
				//缓存里面有直接去缓存里面的
				this.turbEarlyWarns = this.allTurbEarlyWarns[(event.first + this.pageSize) / this.pageSize]
			} else {
				//缓存里面没有调接口
				this.initWarningList(this.event);
				this.sortField = this.event.sortField;
				this.sortOrder = this.event.sortOrder;
			}
		}, 500);


	}

	/**
	* 得到选中风场风机集合
	*
	* @type {Device[]}@memberof TurbineDataListComponent
	*/

	devices: Device[] = [];
	onSelectedDevicesChange(ev: Device[]) {
		this.turbineIds = [];
		ev.forEach(o => {
			this.turbineIds.push(o.deviceId);
		})

	}


	onSearch() {
		this.allTurbEarlyWarns = [];
		this.initWarningList(this.event);
		// this.dt.exportCSV()

	}

	onClickHeader(n: number) {
		this.active = n;
	}

	initWarningList(event) {
		this.isShowBar = true;

		if (this.endTime > new Date()) {
			alert('结束时间不能大于当前时间');
			return;
		}
		if (this.startTime > this.endTime) {
			alert('起始时间不能大于结束时间');
			return;
		}

		this.turbEarlyWarns = [];
		this.turbEarlyWarnService.getTurbineWarns(this.turbineIds, this.startTime, this.endTime, event.first, this.pageSize, event.sortField, event.sortOrder, this.divWarnName)
			.then(response => {
				let res = response.data;
				this.count = response.count;
				if (!res) { return false; };
				this.warms = [];
				this.turbEarlyWarns = [];
				this.original = [];
				this.original = [...res];
				this.original.forEach(o => {
					const warm: WarmEarly = {
						stateName: o.stateName,
						stateColor: o.stateColor,
						tagDesc: o.farmName + o.deviceName + o.tagName,
						startTime: o.startTime,
						endTime: o.endTime,
						maxVal: o.maxVal,
						minVal: o.minVal
					};
					this.warms.push(warm);
				});
				this.turbEarlyWarns = [...this.warms];
				this.isShowBar = false;

				//把当前页的数据缓存起来
				this.allTurbEarlyWarns[(event.first + this.pageSize) / this.pageSize] = this.turbEarlyWarns;
				//缓存下一页数据
				if (!this.allTurbEarlyWarns[((event.first + this.pageSize) / this.pageSize) + 1]) {
					//下一页没有内容，调接口进行缓存；
					this.turbEarlyWarnService.getTurbineWarns(this.turbineIds, this.startTime, this.endTime, event.first + this.pageSize, this.pageSize, event.sortField, event.sortOrder, this.divWarnName)
						.then(response => {
							// { event.first, this.limit},{this.turbineIds,this.divWarnName,this.startTime, this.endTime},{event.sortField, event.sortOrder}
							let res = response.data;
							if (!res) { return false; };
							this.warms = [];
							this.original = [...res];
							this.original.forEach(o => {
								const warm: WarmEarly = {
									stateName: o.stateName,
									stateColor: o.stateColor,
									tagDesc: o.farmName + o.deviceName + o.tagName,
									startTime: o.startTime,
									endTime: o.endTime,
									maxVal: o.maxVal,
									minVal: o.minVal
								};
								this.warms.push(warm);
							});
							//把当前页的数据缓存起来
							this.allTurbEarlyWarns[((event.first + this.pageSize) / this.pageSize) + 1] = [...this.warms];


						})
						.catch(error => {
							// this._message.info('数据初始化失败' + error, { nzDuration: 3000 });
						});
				}

			})
			.catch(error => {
				// this._message.info('数据初始化失败' + error, { nzDuration: 3000 });
				this.isShowBar = false;
			});

	}


	exportData() {

		// 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
		var html = '<html><head><meta charset="utf-8" /></head><body >' + document.getElementById('ex-tab-turbEarlyWarns').outerHTML + '</body></html>';

		// 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
		var blob = new Blob([html], { type: 'application/vnd.ms-excel' });
		// var a = document.getElementsByTagName('a')[0];
		// 利用URL.createObjectURL()方法为a元素生成blob URL
		var href = URL.createObjectURL(blob);
		document.getElementById('ex').setAttribute('href', href);

		// // 设置文件名，目前只有Chrome和FireFox支持此属性
		document.getElementById('ex').setAttribute('download', '历史预警.xls');
		// a.download = '实际功率曲线.xls';
		// a.click();
		// document.getElementById('ex').click();

	}
	/**

		initWarningList() {
			if (this.turbineIds.length <= 0) {
				alert('请选择设备');
				return;
			}
			if (this.endTime > new Date()) {
				alert('结束时间不能大于当前时间');
				return;
			}
			if (this.startTime > this.endTime) {
				alert('起始时间不能大于结束时间');
				return;
			}
			this.turbEarlyWarns = [];
			this.turbEarlyWarnService.getTurbineWarns(this.turbineIds, this.startTime, this.endTime)
				.then(res => {
					if (!res) { return false; };
					this.warms = [];
					this.turbEarlyWarns = [];
					this.original = [];
					this.original = [...res];
					this.original.forEach(o => {
						const warm: WarmEarly = {
							stateName: o.stateName,
							stateColor: o.stateColor,
							tagDesc: o.farmName + o.deviceName + o.tagName,
							startTime: o.startTime,
							endTime: o.endTime,
							maxVal: o.maxVal,
							minVal: o.minVal
						};
						this.warms.push(warm);
					});
					this.turbEarlyWarns = [...this.warms];
					this.groupByStateName([...this.warms]);
					this.onCountWarms([...res]);
				})
				.catch(error => {
					this._message.info('数据初始化失败' + error, { nzDuration: 3000 });
				});
		}

		 */


	// onCountWarms(turbEarlyWarns: TurbEarlyWarn[]) {
	// 	// 按状态-测点-风机统计预警数量
	// 	this.warmCountData = [];
	// 	const counts: WarmCount[] = [];
	// 	let warmCountsData: WarmCount[] = [];

	// 	// 按stateName分组
	// 	const listState = new List(turbEarlyWarns);
	// 	const groupsState = listState.GroupBy(grouper => grouper.stateName, mapper => mapper);
	// 	const stateNames = Object.getOwnPropertyNames(groupsState);
	// 	stateNames.forEach(stateName => {
	// 		const stateList = new List<TurbEarlyWarn>(Object.getOwnPropertyDescriptor(groupsState, stateName).value);
	// 		const stateListArray = new List<TurbEarlyWarn>(Object.getOwnPropertyDescriptor(groupsState, stateName).value).ToArray();

	// 		// stateName分组后，按tagName分组
	// 		const listTags = new List(stateListArray);
	// 		const groupsTag = listTags.GroupBy(grouper => grouper.tagName, mapper => mapper);

	// 		const tags = Object.getOwnPropertyNames(groupsTag)
	// 		tags.forEach(tag => {
	// 			const tagList = new List<TurbEarlyWarn>(Object.getOwnPropertyDescriptor(groupsTag, tag).value);
	// 			const tagListArray = new List<TurbEarlyWarn>(Object.getOwnPropertyDescriptor(groupsTag, tag).value).ToArray();

	// 			// tagName分组后，按照风机分组；
	// 			const listTurbs = new List(tagListArray);
	// 			const groupsTurb = listTurbs.GroupBy(grouper => grouper.deviceName, mapper => mapper);
	// 			const turbineNames = Object.getOwnPropertyNames(groupsTurb);
	// 			turbineNames.forEach(turbineName => {
	// 				const turbList = new List<TurbEarlyWarn>(Object.getOwnPropertyDescriptor(groupsTurb, turbineName).value);
	// 				const turbListArray = new List<TurbEarlyWarn>(Object.getOwnPropertyDescriptor(groupsTurb, turbineName).value).ToArray();
	// 				const timeWork = turbList.Sum(o => new Date(o.endTime).getTime() - new Date(o.startTime).getTime());
	// 				const warmCountData: WarmCount = {
	// 					stateName: stateName,
	// 					tagDesc: turbListArray[0].farmName + turbineName + tag,
	// 					warmsCount: turbList.Count(),
	// 					warmWorkTime: Number((timeWork / this.h).toFixed(2))
	// 				};
	// 				counts.push(warmCountData);
	// 			});
	// 		});
	// 	});
	// 	this.warmCountData = [...counts];
	// 	this.warmCountFilterData = [...this.warmCountData];
	// }

	// onKeyUp(e) {
	// 	if (this.divWarnName !== '' && this.divWarnName) {
	// 		this.divWarnName.trim(); // 去掉收尾空格
	// 		this.turbEarlyWarns = this.warms.filter(o => o.tagDesc.indexOf(this.divWarnName) !== -1);
	// 		this.warmCountFilterData = this.warmCountData.filter(o => o.tagDesc.indexOf(this.divWarnName) !== -1);
	// 	} else {
	// 		this.turbEarlyWarns = [];
	// 		this.warmCountFilterData = [];
	// 		this.turbEarlyWarns = [...this.warms];
	// 		this.warmCountFilterData = [...this.warmCountData];
	// 	}
	// }

	// private groupByStateName(turbEarlyWarns: WarmEarly[]) {
	// 	// 构建状态数据集合
	// 	let list: List<WarmEarly> = new List(turbEarlyWarns);
	// 	// 按状态分类分组
	// 	let groups = list.GroupBy(grouper => grouper.stateName, mapper => mapper);
	// 	let stateNames = Object.getOwnPropertyNames(groups);

	// 	this.stateGroups = [];


	// 	stateNames.forEach(element => {
	// 		let elementList = new List<WarmEarly>(Object.getOwnPropertyDescriptor(groups, element).value);  // ????
	// 		let stateCount = elementList.Count();
	// 		let stateToGroup: StateGroups = {

	// 			stateGroupName: element,
	// 			stateCount: stateCount,
	// 			stateColor: elementList['_elements'][0].stateColor
	// 		};
	// 		this.stateGroups.push(stateToGroup);
	// 	});
	// }

	// public onClickState(event: HTMLInputElement, state: StateGroups) {
	// 	state.isChecked = event.checked;
	// 	this.stateFilter(state);
	// }


	// private stateFilter(state: StateGroups) {
	// 	this.turbEarlyWarns = [];
	// 	// 当前状态类别下的数据
	// 	let checkedState = this.stateGroups.filter(o => o.isChecked);
	// 	let checkedLen = checkedState.length;
	// 	if (checkedLen > 0) {
	// 		checkedState.forEach(o => {
	// 			var currStateDatas = this.warms.filter(k => k.stateName === o.stateGroupName);
	// 			this.turbEarlyWarns.push(...currStateDatas);
	// 		})
	// 	} else {
	// 		this.turbEarlyWarns = this.warms;
	// 	}

	// }


}
interface WarmEarly {
	stateName: string;
	stateColor: string;
	tagDesc: string;
	startTime: string;
	endTime: string;
	maxVal: number;
	minVal: number;
}



// WEBPACK FOOTER //
// ./src/app/module/alarm/early-warn-search/warn-search.component.ts